#include "ImageSprite.h"
#include "log.h"

ImageSprite * ImageSprite::create(CCTexture2D *texture, int i, int j,int itemWidth,int itemHeight) {
	LOG_FUNCTION_NAME;
	ImageSprite *imageSprite = new ImageSprite();
	if (imageSprite) {
		imageSprite->m_itemWidth = itemWidth;
		imageSprite->m_itemHeight = itemHeight;
		imageSprite->initWithTexture(texture,CCRectMake(j * itemWidth, i* itemHeight, itemWidth, itemHeight));
		imageSprite->autorelease();
		return imageSprite;
	}
	CC_SAFE_DELETE (imageSprite);
	return NULL;
}

void ImageSprite::onInit() {

}

bool ImageSprite::init(){
	CCSprite::init();
}

bool ImageSprite::containsTouchLocation(CCTouch *touch) {
	CCPoint point = touch->getLocation();
	point = getParent()->convertToNodeSpace(point);
	return this->rect().containsPoint(point);
}

CCRect ImageSprite::rect() {
	CCPoint point = getPosition();
	CCPoint anchorPoint = getAnchorPoint();
	CCSize size = displayFrame()->getOriginalSize();
	CCRect rect = CCRectMake(point.x - size.width * anchorPoint.x,
            point.y - size.height * anchorPoint.y,
            size.width, size.height);
	return rect;
}

CCRect ImageSprite::nextRect(CCPoint point) {

	CCPoint anchorPoint = getAnchorPoint();
	CCSize size = this->displayFrame()->getOriginalSize();

	CCRect rect = CCRectMake(point.x - size.width * anchorPoint.x,
	            point.y - size.height * anchorPoint.y,
	            size.width, size.height);
	return rect;
}

bool ImageSprite::nextContainsTouchLocation(CCTouch *touch) {
	CCPoint point = touch->getLocation();
	point = getParent()->convertToNodeSpace(point);
	CCPoint p1 = ccpAdd(this->getPosition(), ccp(m_itemWidth, 0));
	CCPoint p2 = ccpAdd(this->getPosition(), ccp(-m_itemWidth, 0));
	CCPoint p3 = ccpAdd(this->getPosition(), ccp(0, m_itemHeight));
	CCPoint p4 = ccpAdd(this->getPosition(), ccp(0, -m_itemHeight));
	if (this->nextRect(p1).containsPoint(point)
			|| this->nextRect(p2).containsPoint(point)
			|| this->nextRect(p3).containsPoint(point)
			|| this->nextRect(p4).containsPoint(point)) {
		return true;
	} else
		return false;
}

void ImageSprite::setFinalPos(int finalPos) {

	m_finalPos = finalPos;
}

int ImageSprite::getFinalPos() {
	return m_finalPos;
}

void ImageSprite::setRandomPos(int randomPos) {
	m_randomPos= randomPos;
}

int ImageSprite::getRandomPos() {
	return m_randomPos;
}

void ImageSprite::setCurrentPos(int currentPos){
	m_currentPos = currentPos;
}

int ImageSprite::getCurrentPos(){
	return m_currentPos;
}

